import {
	exhibitLogin,
	getInfo,
	logout
} from '@/api/user.js'
import {
	getOss,
	getAppParam
} from '@/api/updataFile'
import {
	parseTime
} from '@/utils/index.js'
const user = {
	state: {
		loginForm: {},
		token: null,
		tokenForm: null,
		oss: null,
		disable: false,
		ossParams: null
	},
	mutations: {
		"SET_LOGIN": (state, data) => {
			state.loginForm = data;
		},
		"SET_TOKEN": (state, token) => {
			state.token = token;
		},
		"SET_TOKENFORM": (state, tokenForm) => {
			state.tokenForm = tokenForm;
		},
		"SET_OSS": (state, config) => {
			state.oss = config
		},
		"SET_STEP": (state, step) => {
			state.loginForm.operationStep = step;
		},
		"SET_ROlE": (state, role) => {
			state.loginForm.userType = role;
		},
		"SET_CAN": (state, flag) => {
			state.disable = flag;
		},
		"SET_OSSPARAMS": (state, config) => {
			state.ossParams = config
		},
	},
	actions: {
		//登录信息
		async setLogin({
			commit,
			dispatch
		}, form) {
			try {
				const res = await exhibitLogin(form)
				commit('SET_TOKEN', res.access_token)
				commit('SET_TOKENFORM', res)
				await dispatch('getInfo', res.user)
				return Promise.resolve(res.user)
			} catch (e) {
				//TODO handle the exception
				return Promise.reject(e)
			}
		},
		async getInfo({
			commit,dispatch,getters
		}, loginForm) {
			try {
				const user = loginForm || await getInfo({
					showLoading: true
				});
				if (!user) return Promise.reject("用户信息获取失败")
				if (user.isClerk) { // 如果是dm或者店长 则usertype为空
					user.userType = ''
				}
				// 回显红点
				const redNotif = uni.getStorageSync(`${user.hxUsername}notif`)
				if (redNotif) {
					dispatch('setRedNotif',redNotif)
				}
				console.log(redNotif,'redNotif',`${user.hxUsername}notif`) // 更新红点
				commit('SET_LOGIN', user)
				return Promise.resolve(user)
			} catch (e) {
				return Promise.reject(e)
			}
		},
		//设置当前步骤
		setUserStep({
			commit
		}, step) {
			commit('SET_STEP', step)
		},
		//设置当前步骤
		setUserRole({
			commit
		}, role) {
			commit('SET_ROlE', role)
		},
		//token
		setToken({
			commit
		}, token) {
			commit('SET_TOKEN', token)
		},
		//退出登录
		loginOut({
			commit
		}) {
			logout().then(res => {
				commit('SET_LOGIN', {})
				commit('SET_TOKEN', null)
				commit('SET_TOKENFORM', null)
				uni.removeTabBarBadge({
					index: 3
				})
			})
		},
		//获取oss信息
		getOss({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				state.oss && state.oss.dir === parseTime('{y}-{m}-{d}') + '/' && resolve()
				getOss().then(data => {
					commit('SET_OSS', data)
					resolve()
				}).catch(reject)
			})
		},

		//获取oss加载资源信息
		getAppParam({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getAppParam().then(data => {
					commit('SET_OSSPARAMS', data)
					resolve()
				}).catch(reject)
			})
		},
	}
}

export default user
